package cn.gson.school.controller.zhaosheng;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.gson.school.dao.jiaoxue.StudentDao;
import cn.gson.school.dao.xitong.UserDao;
import cn.gson.school.dao.xitong.UserInfoDao;
import cn.gson.school.dao.zhaosheng.FollowupDao;
import cn.gson.school.dao.zhaosheng.InputStudentDao;
import cn.gson.school.entity.jiaoxue.StudentEntity;
import cn.gson.school.entity.xitong.UserEntity;
import cn.gson.school.entity.xitong.UserInfoEntity;
import cn.gson.school.entity.zhaosheng.FollowupEntity;
import cn.gson.school.entity.zhaosheng.InputStudentEntity;
import cn.gson.school.mappers.zhaosheng.FollowupMapper;

/**
 * 签约信息Controller
 */
@Controller
@RequestMapping("/zs-followuprecord")
public class FollowupController {
	@Autowired
	private FollowupMapper followupMapper;

	@Autowired
	private FollowupDao followupDao;

	@Autowired
	private InputStudentDao inputStudentDao;
	@Autowired
	private StudentDao studentDao;
	@Autowired
	private UserInfoDao userinfoDao;

	@Autowired
	private UserDao userDao;

	@RequestMapping("list")
	@ResponseBody
	public Map<String, Object> index(FollowupEntity followEntity, HttpServletRequest request,
			@RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize) {
		System.out.println("跟进记录：" + followEntity);
		HttpSession session = request.getSession();
		UserInfoEntity u = (UserInfoEntity) session.getAttribute("userinfo");
		followEntity.setFollowId(u.getUserInfoId());
		PageHelper.startPage(pageNum, pageSize);
		List<FollowupEntity> pageData = (Page<FollowupEntity>) followupMapper.list(followEntity);

		PageInfo<FollowupEntity> info = new PageInfo<>(pageData);
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}

	@GetMapping("delete/{id}")
	@ResponseBody
	public JSONObject delete(@PathVariable("id") Long id) {
		JSONObject obj = new JSONObject();
		obj.put("success", false);
		FollowupEntity u;
		if (id != null && (u = followupDao.findOne(id)) != null) {
			followupDao.delete(u);
			obj.put("success", true);
		} else {
			obj.put("message", "此用户不存在！");
		}
		return obj;
	}

	/**
	 * 表单
	 */
	@GetMapping({ "zs-addfollowuprecord", "zs-addfollowuprecord/{id}" })
	public String form(@PathVariable(name = "id", required = false) Long id, Model model) {
		if (id != null) {
			FollowupEntity u = followupDao.findOne(id);
			System.out.println("学生：" + u.getInputStuName().getInputStuName());
			if (u != null) {
				model.addAttribute("followupEntity", u);
			}
		}
		return "zhaosheng/zs-addfollowuprecord";
	}

	/**
	 * 就业部分的跟进
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping({ "zs-genjinfollowuprecord", "zs-genjinfollowuprecord/{id}" })
	public String genjing(@PathVariable(name = "id", required = false) Long id, Model model) {
		System.out.println("这是个id：" + id);
		FollowupEntity u = followupDao.jiuyegenjin(id);
		StudentEntity stu = studentDao.findOne(id);
		String name=null;
		System.out.println(stu.getStudentName());
		if (u != null) {
			model.addAttribute("followupEntity", u);
			name=u.getStuId().getStudentName();
		} else{
			name=stu.getStudentName();
		}
		model.addAttribute("stuname",name);
		model.addAttribute("stu",stu);
		model.addAttribute("jiuyegenjin", 1);
		return "zhaosheng/zs-addfollowuprecord";
	}

	/**
	 * 添加跟进信息
	 * 
	 * @throws ParseException
	 */
	@PostMapping("save")
	@ResponseBody
	public Map<String, Object> save(@Valid FollowupEntity followEntity, BindingResult br, HttpServletRequest request)
			throws ParseException {
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		if (br.hasErrors()) {
			obj.put("message", "信息校验失败！");
			obj.put("erros", br.getFieldErrors());
		} else {
			/* 添加，编辑所需获取的信息 */
			String inputstuname = request.getParameter("inputstuName");// 获取学生姓名
			String followWays = request.getParameter("followWays");// 获取跟进方式
			String followContent = request.getParameter("followContent");// 获取跟进内容
			String jiuyegenjin = request.getParameter("jiuyegenjin");// 判断是就业还是录入学生
			String stuid = request.getParameter("stuid");// 判断是就业还是录入学生id
			
			Long userId = Long.parseLong(request.getParameter("userid"));
			UserEntity userEntity = userDao.findOne(userId);// 找到当前用户
			UserInfoEntity userInfoEntity = userinfoDao.findByUserId(userEntity);// 找到当前用户
			String follownextTime = request.getParameter("follownextTime");// 获取下次跟进时间
			System.out.println("就业吗：" + jiuyegenjin);
			System.out.println("id:"+followEntity.getFollowId());
			if (jiuyegenjin.equals("1")) {
				if(followEntity.getFollowId()!= null) {
					followEntity.setFollowId(followEntity.getFollowId());
				}
				System.out.println("id吗：" + stuid);
				StudentEntity stu = studentDao.findOne(Long.valueOf(stuid));
				followEntity.setStuId(stu);
				followEntity.setFollowWays(followWays);
				followEntity.setFollowContent(followContent);
				followEntity.setUserinfoName(userInfoEntity);
				followEntity.setFollownextTime(follownextTime);
				followEntity.setFollowTime((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));
				followEntity.setFollowStuStatus(1);
			} else {
				if (followEntity.getFollowId() == null) {
					if (inputstuname == null) {
						obj.put("message", "学生姓名不能为空！");
						return obj;
					} else if (followContent == null) {
						obj.put("message", "跟进内容不能为空！");
						return obj;
					} else if (follownextTime == null) {
						obj.put("message", "下次跟进时间不能为空！");
						return obj;
					}
					InputStudentEntity student = inputStudentDao.findByInputStuName(inputstuname);
					followEntity.setInputStuName(student);
					followEntity.setFollowWays(followWays);
					followEntity.setFollowContent(followContent);
					followEntity.setUserinfoName(userInfoEntity);
					followEntity.setFollownextTime(follownextTime);
					followEntity.setFollowTime((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));
					followEntity.setFollowStuStatus(-1);
				} else {
					// 编辑的时的两种情况
					// 1、有信息，更新信息
					Long inputStuId = Long.parseLong(request.getParameter("inputstuId"));
					InputStudentEntity inputStuName = inputStudentDao.findOne(inputStuId);// 找到学生
					// 赋值
					followEntity.setInputStuName(inputStuName);
					followEntity.setFollowContent(followEntity.getFollowContent());
					followEntity.setFollowTime((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date()));
					followEntity.setFollowWays(followEntity.getFollowWays());
					followEntity.setFollownextTime(follownextTime);
					followEntity.setUserinfoName(userInfoEntity);
					followEntity.setFollowStuStatus(-1);

				}
			}
			followupDao.save(followEntity);
			obj.put("success", true);

		}
		return obj;
	}
}
